home *** CD-ROM | disk | FTP | other *** search
- Path: mayne.ugrad.cs.ubc.ca!not-for-mail
- From: c2a192@ugrad.cs.ubc.ca (Kazimir Kylheku)
- Newsgroups: comp.lang.c
- Subject: Re: how to prevent overflow in unsigned?
- Date: 16 Apr 1996 13:44:01 -0700
- Organization: Computer Science, University of B.C., Vancouver, B.C., Canada
- Message-ID: <4l10qhINN8gu@mayne.ugrad.cs.ubc.ca>
- References: <4l0i9b$efq@gwdu19.gwdg.de>
- NNTP-Posting-Host: mayne.ugrad.cs.ubc.ca
-
- In article <4l0i9b$efq@gwdu19.gwdg.de>,
- Arne Mueller <amuelle3@gwdu19.gwdg.de> wrote:
- >Hello,
- >
- >I've the following problem:
- >
- >I have to write a function (I'm not allowed to use the standard functions of stdlib!)
- >that reads an unsigned int from stdin (using getchar).
-
- homework?
-
- >My question: How to recognize an overflowWh
- >If the number is bigger than UINT_MAX, the variable that saves the number
- >is not set to zero.
-
- That's because you aren't setting it to zero.
-
- >some code ... :
- >
- >IO_STATUS unsigned_read(unsigned int *i)
- >{
- >
- > int c;
- > unsigned int x;
- > unsigned int i_old;
-
- Turn on all your compiler warnings. If it's any good, it will warn you that you
- are using i_old without initializing it.
-
- > IO_STATUS stat = IN_NOK;
- >
- > i_alt = *i = 0;
-
- Ah, since ``alt'' is German for ``old'', I see you are typing code off the top
- of your head. No American compiler will recognize the mixup, and permit the
- i_old lvalue to be accessed as i_alt.
-
- > while (isdigit((c = getchar())) != 0)
- > {
- > x = (unsigned int) c - 48; /* 48 is ASCII 0 */
-
- Yes, 48 is ascii 0! But why make your code ascii specific, when you can
- perfectly well write: c - '0'; The C language standard guarantees that the
- character values for the digits '0'-'9' are consecutive, increasing integers,
- so subtracting '0' from a character to obtain the digit value is portable.
-
- > *i = *i * 10 + x;
- >
- > if (*i <= i_old)
- > {
- > puts("too big!");
- > return IN_NOK;
- > }
- > i_old = *i;
- > stat = IN_OK;
-
- You don't need to repeatedly assign to ``stat''. You never use it anyway.
-
- > }
- >
- > return OK;
-
- I thought it was IN_OK. Which one is it?
-
- Repost your program after you have massaged it to the point that it actually
- compiles. We can't move on to analyzing the deeper semantics of something that
- doesn't even meet simple syntactic or semantic constraints.
- --
- I'm not really a jerk, but I play one on Usenet.
-